<?php

class Admin_UserController extends Zend_Controller_Action
{

    private $_model = null;

    public function init()
    {
        /* Initialize action controller here */
        $this->_model = new Application_Model_DbTable_User();
        
    }

    public function indexAction()
    {
        // action body
        $form = new Application_Form_ChangePass();
        $this->view->form = $form;
        
    }
    
    public function editAction()
    {
        $form = new Application_Form_User();
        $form->username->setAttrib("disable",true);
        $form->username->setRequired(false);        
        $form->groups_id->setRequired(false);        
        $form->removeElement("password");
        $form->removeElement("repassword");
        $form->submit->setLabel("Lưu");
        $mdGroup = new Application_Model_DbTable_UserGroup();
        $groups = $mdGroup->fetchAll("groups_status=1");
        foreach($groups as $group)
        {
            $ops[$group->idgroups] = $group->groups_name;
        }
        $form->groups_id->setMultiOptions($ops);
        $iduser = $this->_request->getParam("iduser");
        $user = $this->_model->find($iduser)->current();
        
        //User với id=1 là user mặc định
        if($user->idusers==1)
        {
            $form->groups_id->setAttrib("disable",true);
        }
        $date = new Zend_Date($user->birthday);
        $user->birthday = $date->toString("dd/MM/Y");
        $form->removeElement("idusers");
        $form->populate($user->toArray());
        $this->view->user_image = $user->image;
        if($this->_request->isPost())
        {
            if($form->isValid($_POST))
            {
                $datas = $form->getValues();
                unset($datas['username']);
                unset($datas['user_image']);
                if(empty($datas['birthday']))
                {
                    $datas['birthday'] = NULL;
                }
                else
                {
                    $date->setDate($datas['birthday'],"dd/MM/Y");
                    $datas['birthday'] = $date->toString("Y-MM-dd");
                }
                
                if($user->idusers==1)
                {
                    unset($datas['groups_id']);
                }
                    
                if($form->user_image->isUploaded())
                {
                    if(!empty($user->image))
                    {
                        unlink($form->user_image->getDestination()."/".$user->image);
                    }
                    $form->user_image->receive();
                    $image_name = basename($form->user_image->getFilename());
                    $image_path = $form->user_image->getDestination();
                    if(is_file($image_path."/".$image_name))
                    {
                        $image = new Cms_File_Image($image_path."/".$image_name);
                        $image->setDestinationPath($image_path."/");
                        $datas['image'] = $image->CopyResize("200x220");
                        unlink($image_path."/".$image->newname);
                    }
                }                    
                foreach($datas as $key=>$value)
                {
                    $user->$key = $value;
                }
                $user->save();
                $this->_redirect($this->view->url(array(
                    "module"=>"admin",
                    "controller"=>"user",
                    "action"=>"index"
                ),null, true));                 
            }
            else
            {
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        $this->view->form = $form;
    }
    
    
    public function addAction()
    {
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/jquery.validate.min.js")
        );
        /*-----------------Kiểm tra username tồn tại------------------*/
        $checkUserName = $this->_request->getParam("checkuser",null);
        if($checkUserName!=null && $checkUserName==true)
        {
            $username = $this->_request->getParam("username");
            $select = $this->_model->select();
            $select->where("username=?",$username);
            $users = $this->_model->fetchAll($select);
            $result = false;
            if($users->count()<=0)
            {
                $result = true;
            }
            $this->_helper->json->sendJson($result);
        }
        
        /*Sử lý thêm user*/        
        $form = new Application_Form_User();
        $ops = array(0=>"Chọn nhóm...");
        $mdGroup = new Application_Model_DbTable_UserGroup();
        $groups = $mdGroup->fetchAll($mdGroup->select()->where("groups_status=?",1));
        foreach($groups as $group){
            $ops[$group->idgroups] = $group->groups_name;
        }
        $form->groups_id->setMultiOptions($ops)->setValue(1);
        
        if($this->_request->isPost())
        {
            if($form->isValid($_POST))
            {
                $datas = $form->getValues();
                $users = $this->_model->fetchAll($this->_model->select()->where("username=?",$datas['username']));
                if($users->count() <=0)
                {
                    if(empty($datas['birthday']))
                    {
                        unset($datas['birthday']);
                    }
                    else
                    {
                        $date = new Zend_Date($datas['birthday']);
                        $datas['birthday'] = $date->toString("Y-MM-dd");
                    }
                    $row = $this->_model->createRow($datas);
                    if($row->username != "" && $row->password==$datas['repassword'] && $row->groups_id!=0)
                    {
                        $row->password = md5($row->password);
                        if($form->user_image->isUploaded())
                        {
                            $form->user_image->receive();
                            $image_name = basename($form->user_image->getFilename());
                            $image_path = $form->user_image->getDestination();
                            if(is_file($image_path."/".$image_name))
                            {
                                $image = new Cms_File_Image($image_path."/".$image_name);
                                $image->setDestinationPath($image_path."/");
                                $row->image = $image->CopyResize("200x220");
                                unlink($image_path."/".$image->newname);
                            }
                        }                    
                        $row->save();  
                        $this->_redirect($this->view->url(array(
                            "module"=>"admin",
                            "controller"=>"user",
                            "action"=>"index"
                        ),null, true));                     
                    }   
                }
            }
            else
            {                
                $errors = $form->getMessages();
                foreach($errors as $key=>$value)
                {
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        $this->view->form = $form;
    }
    
     public function delAction()
    {
        $id = $this->_request->getParam("id",null);
        $result = null;
        if($id!=null)
        {
            $row = $this->_model->find($id)->current();
            if(is_file(APPLICATION_PATH."/../public/images/profile/$row->image"))
            {
                unlink(APPLICATION_PATH."/../public/images/profile/$row->image");
            }
            $result = $row->delete();
        }
        $this->_helper->json->sendJson($result);
    }


    public function listAction()
    {
                
        // action body
         $sortby = $this->_request->getParam("sortby",null);
         $sorttype = $this->_request->getParam("sorttype", "asc");
         $filter_field = $this->_request->getParam("filter_field", null);
         $filter_value = $this->_request->getParam("filter_value");
         $this->view->sort = array("by"=>$sortby, "type"=>$sorttype);
         
         $filter = null;
         if(!empty($filter_field))
         {
            $filter[$filter_field] = $filter_value;
         }
         $adapter = $this->_model->fetchPaginatorAdapter($filter,$sortby,$sorttype);
         $paginator = new Zend_Paginator($adapter);
         
         //Show 10 dòng trên 1 trang
         $paginator->setItemCountPerPage(10);
         $page = $this->_request->getParam("page",1);
         $paginator->setCurrentPageNumber($page);
         $this->view->datas = $paginator;
         
         $this->_helper->layout()->disableLayout();
         $this->_response->clearBody();
    }
    
    public function changePassAction()
    {
        if($this->_request->isPost())
        {
            $iduser = $this->_request->getParam("iduser");
            $pass = $this->_request->getParam("password");
            $repass = $this->_request->getParam("repassword");
            $result = false;
            if($pass == $repass && $pass!="")
            {
                $this->_model->update(array("password"=>md5($pass)), "idusers=$iduser");
                $result = true;
            }
            $this->_helper->json->sendJson($result);
        }

        $this->_helper->layout()->disableLayout();
        $this->_response->clearBody();
    }
    
    public function lockUserAction()
    {
        $choice = $this->_request->getParam("choice");
        if(!empty($choice)){
            $iduser = intval($this->_request->getParam("id"));
            $rowuser = $this->_model->find($iduser)->current();
            $n_status = ($rowuser->status)?0:1;
            if($choice=="multi"){
                $result = $this->_model->update(array("status"=>$n_status),"idusers=$iduser");
                $this->_helper->json->sendJson($result);
            }
        }
    }
    
    public function loginAction()
    {
        $lauout = Zend_Layout::getMvcInstance();
        $lauout->setLayout("login");
        
        if($this->_request->isPost())
        {
            $username = $this->_request->getParam("username", "");
            $password = $this->_request->getParam("password", "");
            
            if($username!="")            
            {
                
                $auth = Zend_Auth::getInstance();
                $autAdapter = new Zend_Auth_Adapter_DbTable(null, "users", "username", "password");            
                $autAdapter->setIdentity($username)
                           ->setCredential(md5($password));
                $select = $autAdapter->getDbSelect();
                $select->where("status=?",1);                
                $result = $auth->authenticate($autAdapter);                
                if($result->isValid())
                {
                    $store = $auth->getStorage();
                    $store->write($autAdapter->getResultRowObject(array(
                        "idusers","username","fullname","groups_id"
                    )));
                    return $this->_redirect($this->view->url(array(
                        "module"=>"admin","controller"=>"index","action"=>"index"     
                    ),"default"));
                }   
                else
                {
                    $this->view->has_err = true;
                }                
            }
            else
            {
                $this->view->has_err = true;
            }                
        }   
    }
    
    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        return $this->_redirect("/admin/login");
    }
}













